﻿Imports System.Data.SqlClient
Imports System.Net.Sockets
Imports System.IO

Public Class Receiver
#Region "MAIN"
    Sub GetOpenDataWeb()

    End Sub
    Sub GetOpenData()
        'ToolStripStatusLabel3.Text = 0
        'ToolStripStatusLabel5.Text = 0

        ToolStripStatusLabel1.Text = "Collecting Orders.."
        Try
            ToolStripStatusLabel1.Text = "Checking for new orders.."
            Dim myConn As SqlConnection
            Dim myCmd As SqlCommand
            Dim myReader As SqlDataReader
            'append("Connecting to Server..")
            myConn = New SqlConnection(mainform.ConnectionString)
            ' MsgBox("SELECT * from [Management_Info_Sys].[dbo].[delivery_items] where status='OPEN' and timestamp between '" & Today.AddDays(-1) & "' and '" & Today.AddDays(1) & "'")
            'append("Collecting New Data..")
            myCmd = myConn.CreateCommand
            myCmd.CommandText = "SELECT TOP 50 * from " & mainform.DBTable & " where status='OPEN' and timestamp between '" & Today.AddDays(mainform.DateFromGetMyItems) & "' and '" & Today.AddDays(1) & "' and storename ='" & mainform.MyNAme & "'"
            myConn.Open()
            'append("Reading..")
            myReader = myCmd.ExecuteReader()

            Do While myReader.Read()
                'CheckDuplicate Order by dKey
                Dim Duplicate As Boolean = False
                For Each order As orders In FlowLayoutPanel1.Controls
                    If order.dKey = myReader.GetValue(0).ToString Then
                        Duplicate = True
                        'If order.Status <> myReader.GetValue(11).ToString Then
                        '    Try
                        '        order.Dispose()
                        '    Catch ex As Exception
                        '    End Try
                        'Else
                        '    Duplicate = True
                        'End If
                        Exit For
                    End If
                Next
                'append("Checking Integrity..")
                If Duplicate = False Then
                    Dim Serial As String = myReader.GetValue(1).ToString
                    Dim dKey As String = myReader.GetValue(0).ToString
                    Dim Guestname As String = myReader.GetValue(4).ToString
                    Dim GuestAddress As String = myReader.GetValue(5).ToString
                    Dim ContactNo As String = myReader.GetValue(6).ToString
                    Dim order_ As String = myReader.GetValue(7).ToString
                    Dim totalBill As String = myReader.GetValue(8).ToString
                    Dim specialIns As String = myReader.GetValue(9).ToString
                    Dim ChangeFor As String = myReader.GetValue(10).ToString
                    Dim Status As String = myReader.GetValue(11).ToString
                    Dim DateSent As String = myReader.GetValue(12).ToString
                    Dim Sender As String = myReader.GetValue(15).ToString
                    Dim DateModified As String = myReader.GetValue(14).ToString
                    orderfrm = New orders
                    orderfrm.DateModified = DateModified
                    orderfrm.mainform = mainform
                    orderfrm.dKey = dKey
                    orderfrm.Serial = Serial
                    orderfrm.Status = Status
                    orderfrm.Guestname = Guestname
                    orderfrm.GuestAddress = GuestAddress
                    orderfrm.ContactNo = ContactNo
                    orderfrm.order_ = order_
                    orderfrm.totalBill = totalBill
                    orderfrm.ChangeFor = ChangeFor
                    orderfrm.DateSent = DateSent
                    orderfrm.sender_ = Sender
                    orderfrm.specialIns = specialIns
                    'append("New Order Recieved!")
                    Dim Invoker As New MethodInvoker(AddressOf AddControl)
                    Me.Invoke(Invoker)
                    ToolStripStatusLabel3.Text += 1
                    WindowState = FormWindowState.Normal
                    Media.SystemSounds.Exclamation.Play()

                End If
            Loop
            myReader.Close()
            myConn.Close()
            'append("Done checking new orders! Connection Closed.")
        Catch ex As Exception
            'MsgBox(ex.Message)
        End Try
        Try
            If mainform.IncludeRead = True Then
                GetReadData()
            End If
            If mainform.IncludeClose = True Then
                GetCloseData()
            End If
            ToolStripStatusLabel1.Text = "System Idle"
        Catch ex As Exception
        End Try
    End Sub
    Sub GetReadData()
        Try
            Dim myConn As SqlConnection
            Dim myCmd As SqlCommand
            Dim myReader As SqlDataReader
            ' append("Connecting to Server..")
            myConn = New SqlConnection(mainform.ConnectionString)
            ' MsgBox("SELECT * from [Management_Info_Sys].[dbo].[delivery_items] where status='OPEN' and timestamp between '" & Today.AddDays(-1) & "' and '" & Today.AddDays(1) & "'")
            'append("Collecting New Red Data..")
            myCmd = myConn.CreateCommand
            myCmd.CommandText = "SELECT TOP 50 * from " & mainform.DBTable & " where status='READ' and timestamp between '" & Today.AddDays(mainform.DateFromGetMyItems) & "' and '" & Today.AddDays(1) & "' and storename ='" & mainform.MyNAme & "'"
            myConn.Open()

            myReader = myCmd.ExecuteReader()
            'append("Reading..")
            Do While myReader.Read()
                'CheckDuplicate Order by dKey
                Dim Duplicate As Boolean = False
                For Each order As orders In FlowLayoutPanel1.Controls
                    If order.dKey = myReader.GetValue(0).ToString Then
                        Duplicate = True
                        Exit For
                    End If
                Next
                'append("Checking Integrity..")
                If Duplicate = False Then
                    Dim Serial As String = myReader.GetValue(1).ToString
                    Dim dKey As String = myReader.GetValue(0).ToString
                    Dim Guestname As String = myReader.GetValue(4).ToString
                    Dim GuestAddress As String = myReader.GetValue(5).ToString
                    Dim ContactNo As String = myReader.GetValue(6).ToString
                    Dim order_ As String = myReader.GetValue(7).ToString
                    Dim totalBill As String = myReader.GetValue(8).ToString
                    Dim specialIns As String = myReader.GetValue(9).ToString
                    Dim ChangeFor As String = myReader.GetValue(10).ToString
                    Dim Status As String = myReader.GetValue(11).ToString
                    Dim DateSent As String = myReader.GetValue(12).ToString
                    Dim Sender As String = myReader.GetValue(15).ToString
                    Dim DateModified As String = myReader.GetValue(14).ToString
                    orderfrm = New orders
                    orderfrm.DateModified = DateModified
                    orderfrm.mainform = mainform
                    orderfrm.dKey = dKey
                    orderfrm.Serial = Serial
                    orderfrm.Status = Status
                    orderfrm.Guestname = Guestname
                    orderfrm.GuestAddress = GuestAddress
                    orderfrm.ContactNo = ContactNo
                    orderfrm.order_ = order_
                    orderfrm.totalBill = totalBill
                    orderfrm.ChangeFor = ChangeFor
                    orderfrm.DateSent = DateSent
                    orderfrm.sender_ = Sender
                    orderfrm.specialIns = specialIns
                    Dim Invoker As New MethodInvoker(AddressOf AddControl)
                    Me.Invoke(Invoker)
                    ToolStripStatusLabel3.Text += 1
                End If
            Loop
            myReader.Close()
            myConn.Close()
            'append("Done checking! Connection Closed.")
        Catch ex As Exception

        End Try
        ToolStripStatusLabel1.Text = "Idle"

    End Sub
    Sub GetCloseData()
        Try
            Dim myConn As SqlConnection
            Dim myCmd As SqlCommand
            Dim myReader As SqlDataReader
            ' append("Connecting to Server..")
            myConn = New SqlConnection(mainform.ConnectionString)
            ' MsgBox("SELECT * from [Management_Info_Sys].[dbo].[delivery_items] where status='OPEN' and timestamp between '" & Today.AddDays(-1) & "' and '" & Today.AddDays(1) & "'")
            'append("Collecting New Red Data..")
            myCmd = myConn.CreateCommand
            myCmd.CommandText = "SELECT TOP 50 * from " & mainform.DBTable & " where status='CLOSE' and timestamp between '" & Today.AddDays(mainform.DateFromGetMyItems) & "' and '" & Today.AddDays(1) & "' and storename ='" & mainform.MyNAme & "'"

            myConn.Open()

            myReader = myCmd.ExecuteReader()
            'append("Reading..")
            Do While myReader.Read()
                'CheckDuplicate Order by dKey
                Dim Duplicate As Boolean = False
                For Each order As orders In FlowLayoutPanel1.Controls
                    If order.dKey = myReader.GetValue(0).ToString Then
                        Duplicate = True
                        Exit For
                    End If
                Next
                'append("Checking Integrity..")
                If Duplicate = False Then
                    Dim Serial As String = myReader.GetValue(1).ToString
                    Dim dKey As String = myReader.GetValue(0).ToString
                    Dim Guestname As String = myReader.GetValue(4).ToString
                    Dim GuestAddress As String = myReader.GetValue(5).ToString
                    Dim ContactNo As String = myReader.GetValue(6).ToString
                    Dim order_ As String = myReader.GetValue(7).ToString
                    Dim totalBill As String = myReader.GetValue(8).ToString
                    Dim specialIns As String = myReader.GetValue(9).ToString
                    Dim ChangeFor As String = myReader.GetValue(10).ToString
                    Dim Status As String = myReader.GetValue(11).ToString
                    Dim DateSent As String = myReader.GetValue(12).ToString
                    Dim Sender As String = myReader.GetValue(15).ToString
                    Dim DateModified As String = myReader.GetValue(14).ToString
                    orderfrm = New orders
                    orderfrm.DateModified = DateModified
                    orderfrm.mainform = mainform
                    orderfrm.dKey = dKey
                    orderfrm.Serial = Serial
                    orderfrm.Status = Status
                    orderfrm.Guestname = Guestname
                    orderfrm.GuestAddress = GuestAddress
                    orderfrm.ContactNo = ContactNo
                    orderfrm.order_ = order_
                    orderfrm.totalBill = totalBill
                    orderfrm.ChangeFor = ChangeFor
                    orderfrm.DateSent = DateSent
                    orderfrm.sender_ = Sender
                    orderfrm.specialIns = specialIns
                    Dim Invoker As New MethodInvoker(AddressOf AddControl)
                    Me.Invoke(Invoker)
                    ToolStripStatusLabel5.Text += 1
                End If
            Loop
            myReader.Close()
            myConn.Close()
            'append("Done checking! Connection Closed.")
        Catch ex As Exception

        End Try
        ToolStripStatusLabel1.Text = "Idle"
    End Sub
    Sub GetSpecifyData(iKey As String)
        ToolStripStatusLabel3.Text = 0
        ToolStripStatusLabel5.Text = 0
        ToolStripStatusLabel1.Text = "Collecting Orders.."
        Try
            ToolStripStatusLabel1.Text = "Checking for new orders.."
            Dim myConn As SqlConnection
            Dim myCmd As SqlCommand
            Dim myReader As SqlDataReader
            myConn = New SqlConnection(mainform.ConnectionString)
            ' MsgBox("SELECT * from [Management_Info_Sys].[dbo].[delivery_items] where status='OPEN' and timestamp between '" & Today.AddDays(-1) & "' and '" & Today.AddDays(1) & "'")
            myCmd = myConn.CreateCommand
            myCmd.CommandText = "SELECT TOP 1 * from " & mainform.DBTable & " where serial='" & iKey & "'"
            myConn.Open()
            myReader = myCmd.ExecuteReader()

            Do While myReader.Read()
                'CheckDuplicate Order by dKey
                Dim Duplicate As Boolean = False
                For Each order As orders In FlowLayoutPanel1.Controls
                    If order.dKey = myReader.GetValue(0).ToString Then
                        If order.Status <> myReader.GetValue(11).ToString Then
                            Try
                                order.Dispose()
                            Catch ex As Exception
                            End Try
                        Else
                            Duplicate = True
                        End If
                        Exit For
                    End If
                Next
                If Duplicate = False Then
                    Dim Serial As String = myReader.GetValue(1).ToString
                    Dim dKey As String = myReader.GetValue(0).ToString
                    Dim Guestname As String = myReader.GetValue(4).ToString
                    Dim GuestAddress As String = myReader.GetValue(5).ToString
                    Dim ContactNo As String = myReader.GetValue(6).ToString
                    Dim order_ As String = myReader.GetValue(7).ToString
                    Dim totalBill As String = myReader.GetValue(8).ToString
                    Dim specialIns As String = myReader.GetValue(9).ToString
                    Dim ChangeFor As String = myReader.GetValue(10).ToString
                    Dim Status As String = myReader.GetValue(11).ToString
                    Dim DateSent As String = myReader.GetValue(12).ToString
                    Dim Sender As String = myReader.GetValue(15).ToString
                    Dim DateModified As String = myReader.GetValue(14).ToString
                    orderfrm = New orders
                    orderfrm.DateModified = DateModified
                    orderfrm.mainform = mainform
                    orderfrm.dKey = dKey
                    orderfrm.Serial = Serial
                    orderfrm.Status = Status
                    orderfrm.Guestname = Guestname
                    orderfrm.GuestAddress = GuestAddress
                    orderfrm.ContactNo = ContactNo
                    orderfrm.order_ = order_
                    orderfrm.totalBill = totalBill
                    orderfrm.ChangeFor = ChangeFor
                    orderfrm.DateSent = DateSent
                    orderfrm.sender_ = Sender

                    Dim Invoker As New MethodInvoker(AddressOf AddControl)
                    Me.Invoke(Invoker)
                    ToolStripStatusLabel3.Text += 1
                    WindowState = FormWindowState.Normal
                    Media.SystemSounds.Exclamation.Play()
                End If
            Loop
            myReader.Close()
            myConn.Close()
            'append("Done checking new orders! Connection Closed.")
        Catch ex As Exception
        End Try
        ToolStripStatusLabel1.Text = "System Idle"
    End Sub
    Private Sub AddControl()
        FlowLayoutPanel1.Controls.Add(orderfrm)
    End Sub
#End Region

    Dim orderfrm As New orders
    Public mainform As mainform
    Dim listener As TcpListener
    Private Sub Receiver_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        e.Cancel = True
        WindowState = FormWindowState.Minimized
        mainform.NotifyIcon1.Visible = True
        mainform.NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info
        mainform.NotifyIcon1.BalloonTipTitle = "SDM Client"
        mainform.NotifyIcon1.BalloonTipText = "Relay Delivery Still Renning"
        mainform.NotifyIcon1.ShowBalloonTip(5000)
    End Sub
    Private Sub Receiver_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        My.Settings.Reload()
        Dim mysize As Size
        mysize.Height = My.Computer.Screen.WorkingArea.Height
        mysize.Width = Me.Size.Width
        Me.Size = mysize
        Dim Loc As New Point
        Loc.X = My.Computer.Screen.WorkingArea.Width - mysize.Width
        Loc.Y = 0
        Me.Location = Loc
        GetOpenData()

        'Dim t As New Threading.Thread(AddressOf GetOpenData)
        't.Start()

        listener = New TcpListener(mainform.RealPort)
        'MsgBox(mainform.UsePortToSendSignal)
        If mainform.UsePortToSendSignal = True Then
            ListenerTimer.Enabled = True
            'ListenerTimer.Start()
            listener.Start()
        End If


        Timer1.Interval = mainform.TimerDelay * 1000
        CheckForIllegalCrossThreadCalls = False
       
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Dim t As New Threading.Thread(AddressOf GetOpenData)
        t.Start()
    End Sub

    Private Sub ListenerTimer_Tick(sender As Object, e As EventArgs) Handles ListenerTimer.Tick
        Try
            RecieveMessage()
        Catch ex As Exception
            'MsgBox(ex.ToString)
        End Try
    End Sub
    Dim SenderClient As TcpClient
    Sub RecieveMessage()
        Dim Message As String
        Dim nStart As Integer
        Dim nLast As Integer
        If listener.Pending Then
            Message = ""
            SenderClient = listener.AcceptTcpClient
            Dim Reader As New StreamReader(SenderClient.GetStream())
            While Reader.Peek > -1
                Message &= Convert.ToChar(Reader.Read()).ToString
            End While
            If Message.Contains("</>") Then
                nStart = InStr(Message, "</>") + 4
                nLast = InStr(Message, "<\>")
                Message = Mid(Message, nStart, nLast - nStart)
            End If
            'MsgBox(Message)
            GetSpecifyData(Message)
        End If
    End Sub
End Class